package com.study.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhuyanpeng.zhuyanpeng
 * @Description: : 动态数据源
 * @date :Create in  2019/9/9- 17:21
 * @Version: V1.0
 * @Modified By:
 **/
@Slf4j
public class DynamicRoutingDataSource  extends AbstractRoutingDataSource {
    //定义局部线程变量用来获得数据源标识
    private static final ThreadLocal<String> context = new ThreadLocal<String>(){
        @Override
        protected String initialValue() {
            return DataSourceEnums.FIRST;
        }
    };

    public DynamicRoutingDataSource(DataSource defaultTargetDataSource,
                                    Map<String,DataSource> targetDataSources) {
        //默认数据源
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        //可选数据源
        super.setTargetDataSources(new HashMap<>(targetDataSources));
    }

    @Override
    protected Object determineCurrentLookupKey() {
        log.warn("the current is -->"+context.get());
        return DynamicRoutingDataSource.getDataSource();
    }

    public static  void  setDataSource(String dataSource){
        context.set(dataSource);
    }

    public static  String getDataSource(){
        return context.get();
    }
    //清空标识
    public static  void clearDataSource(){
        context.remove();
    }
}
